package com.fmy.mcsecurity.commons.tools;

import cn.hutool.core.util.RandomUtil;
import com.fmy.mcsecurity.login.service.McUserDetails;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName SecurityTool
 * @Description TODO 高频工具类
 * @createTime 2019/12/9 11:49
 */
public class SecurityTool {

    /**
     * 生成唯一key
     *
     * @param client      客户端标识
     * @param userDetails 用户实体
     * @return 唯一key
     */
    public static String userKey(String client, UserDetails userDetails) {
        if (userDetails instanceof McUserDetails) {
            return userKey(client, ((McUserDetails) userDetails).userId());
        } else {
            throw new IllegalArgumentException("配置出错，请不要继承Security的UserDetails，请继承McUserDetails");
        }
    }

    /**
     * 生成唯一key
     *
     * @param client 客户端标识
     * @param userId 用户id
     * @return 唯一key
     */
    public static String userKey(String client, String userId) {
        return client + "-" + userId;
    }

    /**
     * 获取用户id
     *
     * @param client  客户端标识
     * @param userKey 唯一key值
     * @return 用户id
     */
    public static String getUserId(String client, String userKey) {
        return userKey.replace(client + "-", "");
    }

    /**
     * 根据 timeUnit 追加时间
     *
     * @param time     日期
     * @param p        追加量
     * @param timeUnit 追加量类型，最低支持到秒
     * @return 新的时间
     */
    public static LocalDateTime plus(LocalDateTime time, long p, TimeUnit timeUnit) {
        switch (timeUnit) {
            case SECONDS:
                return time.plusSeconds(p);
            case MINUTES:
                return time.plusMinutes(p);
            case HOURS:
                return time.plusHours(p);
            case DAYS:
                return time.plusDays(p);
            default:
                throw new RuntimeException("无法解析");
        }
    }
}
